package com.xaicode.template.batch.job.normal;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.JobStepBuilder;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;

/**
 * @author beborn
 * @date 2021/12/31 0031 14:52
 */
@Component
public class NestedJobDemo {

    @Resource
    private JobBuilderFactory jobBuilderFactory;

    @Resource
    private StepBuilderFactory stepBuilderFactory;

    @Resource
    private JobLauncher jobLauncher;

    @Resource
    private JobRepository jobRepository;

    @Resource
    private PlatformTransactionManager platformTransactionManager;

    @Bean
    public Job parentJob() {
        return jobBuilderFactory.get("nextedParentJob")
                .start(childJobOneStep())
                .next(childJobTwoStep())
                .build();
    }

    private Step childJobOneStep() {
        return new JobStepBuilder(new StepBuilder("childJobOneStep"))
                .job(childJobOne())
                .launcher(jobLauncher)
                .repository(jobRepository)
                .transactionManager(platformTransactionManager)
                .build();
    }

    private Step childJobTwoStep() {
        return new JobStepBuilder(new StepBuilder("childJobTwoStep"))
                .job(childJobTwo())
                .launcher(jobLauncher)
                .repository(jobRepository)
                .transactionManager(platformTransactionManager)
                .build();
    }

    private Job childJobOne() {
        return jobBuilderFactory.get("childJobOne")
                .start(
                        stepBuilderFactory.get("childJobOneStep")
                                .tasklet(JobHelper.tasklet("NestedJob - child 1", RepeatStatus.FINISHED))
                                .build()
                ).build();
    }

    private Job childJobTwo() {
        return jobBuilderFactory.get("chileJobTwo")
                .start(
                        stepBuilderFactory.get("childJobTwoStep")
                                .tasklet(JobHelper.tasklet("NestedJob - child 2", RepeatStatus.FINISHED))
                                .build()
                ).build();
    }

}
